"""
STS预付费燃气表完整系统演示
展示从售气系统到燃气表的完整工作流程
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from src.sts import STSProtocol, STSCrypto
from src.meter import GasMeter
from src.vending import VendingSystem
import time


def demo_complete_workflow():
    """演示完整的充值工作流程"""
    print("=== STS预付费燃气表完整系统演示 ===")
    print("="*60)
    
    # 创建系统组件
    print("1. 初始化系统组件...")
    vending = VendingSystem()
    meter = GasMeter("123456789")
    
    print(f"   售气系统: {vending.get_system_info()['system_name']}")
    print(f"   燃气表ID: {meter.meter_id}")
    print()
    
    # 2. 操作员登录
    print("2. 操作员登录...")
    login_result = vending.login_operator("OP001", "123456")
    
    if not login_result['success']:
        print(f"   登录失败: {login_result['error']}")
        return
    
    print(f"   登录成功: {login_result['operator_id']}")
    print(f"   会话ID: {login_result['session_id']}")
    print()
    
    # 3. 生成充值令牌
    print("3. 生成充值令牌...")
    amount = 5000  # 50元
    token_result = vending.generate_token("123456789", amount, "CASH")
    
    if not token_result['success']:
        print(f"   令牌生成失败: {token_result['error']}")
        return
    
    token = token_result['token']
    print(f"   令牌生成成功: {token}")
    print(f"   金额: {token_result['amount_formatted']}")
    print(f"   交易ID: {token_result['transaction_id']}")
    print()
    
    # 4. 燃气表充值
    print("4. 燃气表充值...")
    comm_result = meter.start_communication()
    
    if not comm_result['success']:
        print(f"   通信启动失败: {comm_result['error']}")
        return
    
    print(f"   通信启动成功: {comm_result['session_id']}")
    
    # 执行充值
    recharge_result = meter.recharge(token)
    
    if recharge_result['success']:
        print(f"   充值成功!")
        print(f"   充值金额: {recharge_result['amount_formatted']}")
        print(f"   充值前余额: {recharge_result['previous_balance']} 分")
        print(f"   充值后余额: {recharge_result['new_balance_formatted']}")
        print(f"   传输计数器: {recharge_result['transfer_counter']}")
    else:
        print(f"   充值失败: {recharge_result['error']}")
        return
    
    print()
    
    # 5. 验证充值结果
    print("5. 验证充值结果...")
    meter_status = meter.get_meter_status()
    print(f"   当前余额: {meter_status['current_balance_formatted']}")
    print(f"   表计状态: {meter_status['status']}")
    print(f"   报警状态: {meter_status['alarm_status']}")
    print(f"   通信状态: {meter_status['communication_active']}")
    print()
    
    # 6. 模拟用气
    print("6. 模拟用气...")
    consumption_result = meter.simulate_consumption(2.0)  # 2小时用气
    
    if consumption_result['success']:
        print(f"   用气成功!")
        print(f"   用气时长: {consumption_result['duration_hours']} 小时")
        print(f"   用气量: {consumption_result['volume']} 立方米")
        print(f"   费用: {consumption_result['cost_formatted']}")
        print(f"   剩余余额: {consumption_result['new_balance_formatted']}")
    else:
        print(f"   用气失败: {consumption_result['error']}")
    
    print()
    
    # 7. 查看历史记录
    print("7. 查看历史记录...")
    recharge_history = meter.get_recharge_history(5)
    consumption_history = meter.get_consumption_history(5)
    
    print(f"   充值记录数: {len(recharge_history)}")
    if recharge_history:
        latest_recharge = recharge_history[-1]
        print(f"   最近充值: {latest_recharge['amount']} 分")
    
    print(f"   用气记录数: {len(consumption_history)}")
    if consumption_history:
        latest_consumption = consumption_history[-1]
        print(f"   最近用气: {latest_consumption['volume']} 立方米")
    
    print()
    
    # 8. 查看交易统计
    print("8. 查看交易统计...")
    stats_result = vending.get_transaction_statistics(24)
    
    if stats_result['success']:
        stats = stats_result['statistics']
        print(f"   24小时交易统计:")
        print(f"   总交易数: {stats['total_transactions']}")
        print(f"   成功交易数: {stats['completed_transactions']}")
        print(f"   成功率: {stats['success_rate']:.1f}%")
        print(f"   总金额: {stats['total_amount_formatted']}")
    
    print()
    
    # 9. 清理和结束
    print("9. 清理和结束...")
    meter.end_communication()
    vending.logout_operator()
    
    print("   通信已结束")
    print("   操作员已登出")
    print()
    
    print("="*60)
    print("演示完成！STS预付费燃气表系统工作正常。")
    print("="*60)


def demo_error_scenarios():
    """演示错误场景处理"""
    print("\n=== 错误场景演示 ===")
    print("="*40)
    
    # 1. 无效表计ID
    print("1. 测试无效表计ID...")
    vending = VendingSystem()
    vending.login_operator("OP001", "123456")
    
    result = vending.generate_token("12345", 5000, "CASH")  # 太短的表计ID
    print(f"   结果: {result['success']}")
    if not result['success']:
        print(f"   错误: {result['error']}")
    print()
    
    # 2. 无效金额
    print("2. 测试无效金额...")
    result = vending.generate_token("123456789", 0, "CASH")  # 0元
    print(f"   结果: {result['success']}")
    if not result['success']:
        print(f"   错误: {result['error']}")
    print()
    
    # 3. 错误令牌
    print("3. 测试错误令牌...")
    meter = GasMeter("123456789")
    meter.start_communication()
    
    result = meter.recharge("INVALID TOKEN")
    print(f"   结果: {result['success']}")
    if not result['success']:
        print(f"   错误: {result['error']}")
    print()
    
    # 清理
    meter.end_communication()
    vending.logout_operator()


def main():
    """主函数"""
    print("STS预付费燃气表完整系统演示")
    print("本演示将展示从售气系统到燃气表的完整工作流程")
    print()
    
    try:
        # 完整工作流程演示
        demo_complete_workflow()
        
        # 错误场景演示
        demo_error_scenarios()
        
        print("\n演示总结:")
        print("- STS协议实现完整，支持令牌生成和验证")
        print("- 加密解密功能正常，数据安全传输")
        print("- 燃气表模拟器工作正常，支持充值和用气")
        print("- 售气系统功能完整，支持交易管理")
        print("- 错误处理机制完善，系统稳定可靠")
        
    except Exception as e:
        print(f"演示过程中出现错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
